package blackstar.plugin.monitor.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

import blackstar.agent.jvm.JMXProxy;
import blackstar.plugin.monitor.AbstractMonitor;

import com.sun.management.OperatingSystemMXBean;

/**
 * @author raywu (ayufox@gmail.com)
 * 
 */
public class CPUMonitor extends AbstractMonitor
{
	private long prevProcessCpuTime;

	private long prevUpTime;

	private RuntimeMXBean runtimeMXBean = null;

	private OperatingSystemMXBean operatingSystemMXBean = null;

	public CPUMonitor()
	{
		super("cpu");
	}

	public void doInit(JMXProxy jmxProxy) throws Exception
	{
		this.runtimeMXBean = ManagementFactory.newPlatformMXBeanProxy(jmxProxy
				.getLocalMBeanServerConnection(),
				ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);

		this.operatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(
				jmxProxy.getLocalMBeanServerConnection(),
				ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME,
				OperatingSystemMXBean.class);
	}

	public void doOnTimeout()
	{
		long processCpuTime = this.operatingSystemMXBean.getProcessCpuTime();//nanoseconds
		long upTime = this.runtimeMXBean.getUptime();//milliseconds

		if (this.prevProcessCpuTime > 0 && this.prevUpTime > 0)
		{
			long data = (processCpuTime - this.prevProcessCpuTime)
					/ ((upTime - this.prevUpTime) * 1000L);

			report(data);
		}

		this.prevProcessCpuTime = processCpuTime;
		this.prevUpTime = upTime;
	}
}
